<template>
  <div class="plan-selector">
    <el-dialog
      :title="title"
      v-model="visible"
      width="980px"  
      append-to-body
      @close="handleClose"
      destroy-on-close
    >
      <!-- 搜索条件 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
        <el-form-item label="计划编号" prop="planCode">
          <el-input
            v-model="queryParams.planCode"
            placeholder="请输入计划编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="计划名称" prop="planName">
          <el-input
            v-model="queryParams.planName"
            placeholder="请输入计划名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="queryParams.productId"
            placeholder="请选择产品"
            clearable
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择计划状态" clearable>
            <el-option
              v-for="dict in plan_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
            <el-option
              v-for="dict in plan_priority"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格数据 -->
      <el-table 
        v-loading="loading" 
        :data="planList" 
        @row-click="handleRowClick"
        highlight-current-row
        :row-class-name="rowClassName"
        height="400px"
        border
      >
        <el-table-column label="计划ID" align="center" prop="planId" width="80" />
        <el-table-column label="计划编号" align="center" prop="planCode" width="100" />
        <el-table-column label="计划名称" align="center" prop="planName" width="150" />
        <el-table-column label="产品" align="center" prop="productName" width="120" />
        <el-table-column label="生产线" align="center" prop="lineName" width="120" />
        <el-table-column label="计划生产数量" align="center" prop="planQuantity" width="100" />
        <el-table-column label="优先级" align="center" prop="priority" width="80">
          <template #default="scope">
            <dict-tag :options="plan_priority" :value="scope.row.priority"/>
          </template>
        </el-table-column>
        <el-table-column label="计划状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="plan_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click.stop="selectPlan(scope.row)"
              :disabled="!isPlanSelectable(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        :pageSizes="[5, 10, 20, 30]"
        :small="true"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="confirmSelection" :disabled="!selectedPlan">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listPlan, listProduct, listLine } from "@/api/pm/plan";
import { ref, reactive, toRefs, getCurrentInstance, defineProps, defineEmits, watch } from 'vue';

const { proxy } = getCurrentInstance();
const { plan_status, plan_priority } = proxy.useDict('plan_status', 'plan_priority');

// 定义属性和事件
const props = defineProps({
  title: {
    type: String,
    default: '选择生产计划'
  },
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'select']);

// 数据部分
const planList = ref([]);
const productOptions = ref([]); 
const lineOptions = ref([]);
const loading = ref(false);
const visible = ref(false);
const total = ref(0);
const selectedPlan = ref(null);
const selectedRowIndex = ref(null);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planCode: null,
    planName: null,
    productId: null,
    status: null,
    priority: null
  }
});

const { queryParams } = toRefs(data);

// 监听visible变化
watch(() => props.visible, (val) => {
  if (val) {
    // 当弹窗显示时初始化数据
    listProduct().then(response => {
      productOptions.value = response.data;
    });
    getList();
  }
  visible.value = val;
});

// 监听内部visible变化
watch(() => visible.value, (val) => {
  emit('update:visible', val);
});

// 查询计划列表
function getList() {
  loading.value = true;
  listPlan(queryParams.value).then(response => {
    planList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 判断计划是否可选
function isPlanSelectable(plan) {
  // 计划状态：未开始0  进行中1 已完成2 已取消3  暂停4
  // 只有未开始和暂停的计划可以选择
  return plan.status === '0' || plan.status === '4' || plan.status === 0 || plan.status === 4;
}

// 行样式
function rowClassName({row, rowIndex}) {
  let classNames = '';
  
  // 选中行高亮
  if (selectedRowIndex.value === rowIndex) {
    classNames += 'row-selected ';
  }
  
  // 不可选择的计划行样式
  if (!isPlanSelectable(row)) {
    classNames += 'row-disabled';
  }
  
  return classNames;
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 行点击事件
function handleRowClick(row, column, event) {
  // 只有可选择的计划才能被选中
  if (isPlanSelectable(row)) {
    selectedPlan.value = row;
    selectedRowIndex.value = planList.value.findIndex(item => item.planId === row.planId);
  } else {
    // 提示用户该计划不可选择
    const statusMap = {
      '1': '进行中',
      '2': '已完成',
      '3': '已取消'
    };
    const status = statusMap[row.status] || '不可用';
    proxy.$modal.msgWarning(`该计划当前${status}，不可选择`);
  }
}

// 选择计划
function selectPlan(row) {
  if (isPlanSelectable(row)) {
    selectedPlan.value = row;
    selectedRowIndex.value = planList.value.findIndex(item => item.planId === row.planId);
  }
}

// 确认选择
function confirmSelection() {
  if (selectedPlan.value) {
    emit('select', selectedPlan.value);
    handleClose();
  }
}

// 关闭对话框
function handleClose() {
  emit('update:visible', false);
  selectedPlan.value = null;
  selectedRowIndex.value = null;
}

// 打开方法，由父组件调用
function open() {
  visible.value = true;
  reset();
  // 初始化数据
  listProduct().then(response => {
    productOptions.value = response.data;
  });
  
  getList();
}

// 重置方法
function reset() {
  queryParams.value.planCode = null;
  queryParams.value.planName = null;
  queryParams.value.productId = null;
  queryParams.value.status = null;
  queryParams.value.priority = null;
  queryParams.value.pageNum = 1;
  selectedPlan.value = null;
  selectedRowIndex.value = null;
}

// 对外暴露方法
defineExpose({
  open
});
</script>

<style scoped>
.plan-selector .row-selected {
  background-color: #f0f9eb !important;
}

.plan-selector .row-disabled {
  background-color: #f9f9f9 !important;
  color: #999 !important;
  cursor: not-allowed !important;
}

.plan-selector .el-table {
  margin-top: 10px;
  margin-bottom: 10px;
}

.plan-selector .pagination-container {
  margin-top: 10px;
}
</style>